package com.netease.utils;

import com.huaban.analysis.jieba.WordDictionary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @projectName: modeling-dev
 * @package: com.netease.utils
 * @className: FileLoadUtils
 * @author: aochong
 * @description: TODO
 * @date: 2023/4/3 13:15
 * @version: 1.0
 */
public class FileLoadUtils {
    private static final Logger logger = LoggerFactory.getLogger(FileLoadUtils.class);
    private static final String PATH = "user.dict";

    public static void userDictLoad() {
        logger.info("加载自定义词库的信息，开始做自定义词库的分词------->>>>>>>>");
        /**词典路径为Resource/dicts/user.dict*/
        Path path = Paths.get(new File(PATH).getAbsolutePath());
        /**初始化分词库*/
        WordDictionary.getInstance().init(path);
        /**加载自定义的词典进词库*/
        WordDictionary.getInstance().loadUserDict(path);
    }

    /**
     * @param sourceFile:
     * @return void
     * @author aochong
     * @description 行读取文件
     * @date 2023/4/3 22:07
     */
    public static List<String> ReadLineFromFile(File sourceFile) {
        ArrayList<String> list = new ArrayList<>();
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader reader = null;
        try {
            //建立从文件到程序的数据输入(input)流
            fis = new FileInputStream(sourceFile);
            //用 InputStreamReader 包装 byte流，并指定字符编码，让它能够将读出的byte转为字符
            isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
            //增加缓冲功能，输入输出效率更高，并且可以一次读一行
            reader = new BufferedReader(isr);

            if (sourceFile == null) {
                new RuntimeException("文件内容为空！！！");
            }

            String line = null;
            while ((line = reader.readLine()) != null) {
                list.add(line.trim());
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (isr != null){
                    isr.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return list;
    }
}
